package com.emip.service.impl;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.emip.bean.RoleBean;
import com.emip.bean.RoleMenuBean;
import com.emip.dao.MenuDefDAO;
import com.emip.dao.RoleDAO;
import com.emip.dao.RoleMenuDAO;
import com.emip.service.RoleService;

@Service("roleService")
public class RoleServiceImpl implements RoleService {

	@Autowired
	RoleDAO roleDAO;
	@Autowired
	MenuDefDAO menuDefDAO;
	@Autowired
	RoleMenuDAO roleMenuDAO;
	
	public RoleBean addRole(String name, String description) {
		RoleBean newBean = new RoleBean();
		newBean.setName(name);
		newBean.setDescription(description);
		//查重，是否已经有相同的name的记录存在
		//若有重复记录，则返回null
		if (roleDAO.findExist(newBean)) {
			return null;
		}
		int newID = roleDAO.add(newBean);
		newBean.setId(newID);
		return newBean;
	}

	public Boolean deleteRole(int id) {
		// TODO Auto-generated method stub
		roleMenuDAO.deleteRoleMenu(id);
		RoleBean delBean = roleDAO.findByID(id);
		roleDAO.remove(delBean);
		return true;
	}

	public List<RoleBean> getAll() {
		// TODO Auto-generated method stub
		return roleDAO.getAll();
	}

	public RoleBean getRoleByID(int id) {
		// TODO Auto-generated method stub
		return roleDAO.findByID(id);
	}

	public RoleBean updateRole(int id, String name, String description) {
		RoleBean newBean = roleDAO.findByID(id);
		newBean.setName(name);
		newBean.setDescription(description);
		//查重，是否已经有相同的name的记录存在
		//若有重复记录，则返回null
		if (roleDAO.findExist(newBean)) {
			return null;
		}
		roleDAO.update(newBean);
		return newBean;
	}

	public Boolean setRoleMenus(int roleID, String[] menuIDs) {
		roleMenuDAO.deleteRoleMenu(roleID);		
		RoleMenuBean newBean = null;
		for (String menuID : menuIDs) {			
			newBean = new RoleMenuBean();
			newBean.setRole_ID(roleID);
			newBean.setMenu_ID(menuID);
			roleMenuDAO.add(newBean);
		}
		//现在menuIDs中都是二级菜单，要自动加入一级菜单
		List<String> l1menus = roleMenuDAO.l1MenuTobeAdd(roleID);
		for (String l1 : l1menus) {
			newBean = new RoleMenuBean();
			newBean.setRole_ID(roleID);
			newBean.setMenu_ID(l1);
			roleMenuDAO.add(newBean);
		}
		return true;
	}
}
